// import { data } from "./data.js";

// The svg
var svg = d3.select("#my_dataviz"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

// Map and projection
var path = d3.geoPath();
var projection = d3
  .geoMercator()
  .scale(70)
  .center([0, 20])
  .translate([width / 2, height / 2]);

// Data and color scale
var map = new Map();
var colorScale = d3
  //.scaleThreshold()
  .scaleLinear()
  .domain([-50, 0, 60])
  .range(["#ddd", "#ffff", "#e7040f"]);
//.range(["#ddd", "#ffff", "#fa1e1e"]);
//.range(d3.schemeBlues[9]);

let csvData;
let lineData;

// Load external data and boot
Promise.all([
  d3.json(
    "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson"
  ),
  d3
    .csv("real_data.csv", (d) => {
      return {
        code: d.code,
        percent: +d.percent,
      };
    })
    .then(function (Data) {
      csvData = Data;
    }),
  d3
    .csv("line.csv", (d) => {
      return {
        countryname: d.countryname,
        year: +d.year,
        value: +d.value,
      };
    })
    .then(function (Data) {
      lineData = Data;
    }),
]).then(ready);

function ready([topo]) {
  let chartActive = false;

  let mouseOver = function (d, event) {
    d3.selectAll(".Country").transition().duration(200).style("opacity", 0.3);
    d3.select(this)
      .transition()
      .duration(200)
      .style("opacity", 1)
      .style("stroke", "#fff");

    const tooltip = d3
      .select("body")
      .append("div")
      .attr("class", "tooltip")
      .style("position", "absolute")
      .style("background-color", "white")
      .style("padding", "5px")
      .style("border", "1px solid #ccc")
      .style("opacity", 1);
    //console.log(event);
    // 在标签中显示国家名称和数据值
    let countryData = csvData.find((item) => item.code === event.id);
    //console.log(countryData);
    if (countryData.percent > 0) {
      tooltip.html(
        "<strong>" +
          event.properties.name +
          "</strong>" +
          "<br/>" +
          "Data: " +
          countryData.percent +
          "%"
      );
    } else {
      tooltip.html(
        "<strong>" +
          event.properties.name +
          "</strong>" +
          "<br/>" +
          "no figures"
      );
    }

    document.addEventListener("mousemove", function (event) {
      tooltip
        .style("left", event.clientX - 20 + "px") //合并后位置要重调
        .style("top", event.clientY + 1420 + "px");
    });
    // 显示标签动画
    tooltip.transition().duration(200).style("opacity", 1);

    //添加折线图
    // Create a line chart for the selected country
    let countryLineData = lineData.filter(
      (item) => item.countryname === event.properties.name
    );

    // 找到该国家的第一个非缺失数据点的索引
    let startIndex = 0;
    while (
      startIndex < countryLineData.length &&
      !countryLineData[startIndex].value
    ) {
      startIndex++;
    }

    for (let i = startIndex + 1; i < countryLineData.length; i++) {
      if (!countryLineData[i].value && i < countryLineData.length - 1) {
        // 如果当前数据点缺失，使用前后两个数据点的值进行插值
        countryLineData[i].interpolated = true; // 添加标记属性
        countryLineData[i].value = d3.interpolateNumber(
          countryLineData[i - 1].value,
          countryLineData[i + 1].value
        )(0.5);
      } else if (
        !countryLineData[i].value &&
        i === countryLineData.length - 1
      ) {
        // 如果末尾缺值，提前终止插值
        break;
      }
    }

    // 从第一个非缺失数据点开始，将缺失值处插入 null
    for (let i = startIndex + 1; i < countryLineData.length; i++) {
      if (!countryLineData[i].value) {
        countryLineData[i].value = null;
      }
    }

    countryLineData = countryLineData.slice(startIndex);

    if (countryLineData.length > 0) {
      let margin = { top: 10, right: 30, bottom: 130, left: 60 },
        linewidth = 500 - margin.left - margin.right,
        lineheight = 400 - margin.top - margin.bottom;

      let x = d3
        .scaleLinear()
        .domain(
          d3.extent(lineData, function (d) {
            return d.year;
          })
        )
        .range([0, linewidth]);
      let y = d3.scaleLinear().domain([0, 1]).range([lineheight, 0]);

      let line = d3
        .line()
        .x(function (d) {
          return x(d.year);
        })
        .y(function (d) {
          return y(d.value);
        });

      let chart = d3
        .select("#line-chart")
        .attr("width", linewidth + margin.left + margin.right)
        .attr("height", lineheight + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      chart
        .append("path")
        .attr("class", "lineGenerator")
        .datum(countryLineData)
        .attr("d", line);

      xAxis = chart
        .append("g")
        .attr("transform", "translate(0," + lineheight + ")")
        .call(d3.axisBottom(x).tickFormat(d3.format("d")).ticks(5))
        .call((g) =>
          g
            .append("text")
            .attr("x", -60)
            .attr("y", -lineheight)
            .attr("fill", "currentColor")
            .attr("text-anchor", "start")
            .text("index ↑")
        );

      yAxis = chart.append("g").call(d3.axisLeft(y));

      // 过滤掉值为 null 或 undefined 的数据点
      const filteredData = countryLineData.filter(
        (d) => d.value !== null && d.value !== undefined && !d.interpolated
      );

      chart
        .selectAll("circle") //画圆
        .data(filteredData)
        .enter()
        .append("circle")
        .attr("cy", (d) => y(d.value))
        .attr("cx", (d) => x(d.year))
        .attr("r", 2)
        .attr("class", "circle");

      chart
        .selectAll(".text-label") //写数据
        .data(filteredData)
        .enter()
        .append("text")
        .attr("class", "text-label")
        .attr("x", (d) => x(d.year) - 5)
        .attr("y", (d) => y(d.value) - 10)
        .text((d) => d.value);

      chartActive = true;

      const line_title = d3
        .select("#line-chart")
        .append("text")
        .attr("class", "line_title")
        .style("position", "relative")
        .style("color", "black")
        .attr(
          "transform",
          //"translate(" + linewidth + "/2," + lineheight + "/2)"
          "translate(50,320)"
        );

      line_title.html(
        "Gender Gap Index of " +
          event.properties.name +
          " in Political Empowerment"
      );
    }
  };

  let mouseLeave = function (d) {
    d3.selectAll(".Country").transition().duration(200).style("opacity", 0.8);
    d3.select(this).transition().duration(200).style("stroke", "none");
    d3.select(".tooltip").remove();

    if (chartActive) {
      d3.select("#line-chart").selectAll("*").remove();
      d3.select(".line-title").remove();
    }
  };

  // Draw the map
  svg
    .append("g")
    .selectAll("path")
    .data(topo.features)
    .enter()
    .append("path")
    // draw each country
    .attr("d", d3.geoPath().projection(projection))
    // set the color of each country
    .attr("fill", function (d) {
      //console.log(d);
      let countryData = csvData.find((item) => item.code === d.id);
      //console.log(countryData);
      if (countryData) {
        return colorScale(countryData.percent);
      } else {
        return "#ccc";
      }
    })
    .style("stroke", "transparent")
    .attr("class", function (d) {
      return "Country";
    })
    .style("opacity", 0.8)
    .on("click", function () {
      chartActive = !chartActive;
    })
    .on("mouseover", mouseOver)
    .on("mouseleave", mouseLeave);
}

//绘制图例
var legendWidth = 120,
  legendHeight = 8;
var legendScale = d3.scaleLinear().domain([0, 60]).range(["#fff", "#E80020"]);
var legendG = svg
  .append("rect")
  .attr("x", 150)
  .attr("y", 420)
  .attr("width", legendWidth)
  .attr("height", legendHeight)
  .style("fill", "url(#legend-gradient)");
svg
  .append("linearGradient")
  .attr("id", "legend-gradient")
  .attr("gradientUnits", "userSpaceOnUse")
  .attr("x1", 150)
  .attr("y1", 420)
  .attr("x2", 270)
  .attr("y2", 420)
  .selectAll("stop")
  .data(legendScale.ticks())
  .enter()
  .append("stop")
  .attr("offset", function (d) {
    return (d / 63) * 100 + "%";
  })
  .attr("stop-color", function (d) {
    return legendScale(d);
  });
var ticks = legendScale.ticks(10).filter((d) => {
  return [10, 20, 30, 40, 50].includes(d);
});
var tickG = svg
  .selectAll(".tick")
  .data(ticks)
  .enter()
  .append("g")
  .attr("class", "tick")
  .attr("transform", function (d, i) {
    return "translate(" + (170 + (i * 100) / 5) + "," + 420 + ")";
  });
tickG
  .append("line")
  .attr("x1", 0)
  .attr("y1", -1)
  .attr("x2", 0)
  .attr("y2", 10)
  .style("stroke", "#000");
tickG
  .append("text")
  .style("font-size", "6px")
  .attr("x", -5)
  .attr("y", 20)
  .text((d) => {
    return d + "%";
  });
svg
  .append("text")
  .attr("x", 150)
  .attr("y", 415)
  .style("font-size", "7px")
  .style("font-weight", "bold")
  .text("percentage of women in parliament");
// Add title to graph
svg
  .append("text")
  .attr("x", 180)
  .attr("y", 70)
  .attr("text-anchor", "left")
  .style("font-size", "22px")
  .text("% of ");
svg
  .append("text")
  .attr("x", 235)
  .attr("y", 70)
  .attr("text-anchor", "left")
  .style("font-size", "22px")
  .style("fill", "#E16767")
  .style("font-weight", "bold")
  .text("women ");
svg
  .append("text")
  .attr("x", 323)
  .attr("y", 70)
  .attr("text-anchor", "left")
  .style("font-size", "22px")
  .text("in Parliament in 2022");
